﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.library;
using System.ComponentModel.Composition;
using System.Data;
using com.nm;
using com.nm.Helper;
using com.nm.library.Excels;
using com.nm.library.Helper;
using DistributeAPI.Model;
using NHibernateVertica;
using Vertica.Data.VerticaClient;

namespace DistributeAPI.Export
{
    [Export(typeof(ExcelImport))]
    public class ProductionOrderWarehouseExcel : ExcelImport
    {
        private static int num = 0;
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();
        public override ExcelImportType Type => ExcelImportType.PRODUCTIONORDERWAREHOUSE;

        public override Dictionary<string, ImportVerify> DictFields => dictFields;

        /// <summary>
        /// Excel字段映射
        /// </summary>
        private static readonly Dictionary<string, ImportVerify> dictFields = new List<ImportVerify> {
        new ImportVerify{ ColumnName="公司代码",    FieldName="CompanyID" ,DataType=typeof(string),VerifyFunc=(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,200,true,false)},
            new ImportVerify{ ColumnName="生产订单",    FieldName="BillNo" ,DataType=typeof(string),VerifyFunc=(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,200,true,false)},
            new ImportVerify{ ColumnName="仓库编号",    FieldName="StockID" ,DataType=typeof(string),VerifyFunc=(e,extra)=> ExcelImportHelper.GetCellMsg(e.CellValue,e.ColName,200,true,false)},
           }.ToDictionary(e => e.ColumnName, e => e);

        public override object SaveImportData(DataTable dt, Dictionary<string, object> extraInfo, int userId)
        {
            int errorIndex = 0;
            var index = 0;
            #region 构造一个新的Datatable dtError

            //构造一个新的Datatable dtError
            DataTable dtError = new DataTable();
            dtError.Columns.Add("CompanyID", System.Type.GetType("System.String"));
            dtError.Columns.Add("BillNo", System.Type.GetType("System.String"));
            dtError.Columns.Add("StockID", System.Type.GetType("System.String"));

            #endregion 构造一个新的Datatable dtError
            //删除语句集合
            HashSet<string> deleteHashSet = new HashSet<string>();
            var result = new ImportResult();
            try
            {
                //先遍历所有的数据.
                //拼接删除语句放到一个list
                var cmdList = new List<CommandInfo>();
                ProductionOrderWarehouseModel model = new ProductionOrderWarehouseModel();

                #region 构造一个新的Datatable dtNew

                //构造一个新的Datatable dtNew
                DataTable dtNew = new DataTable();
                dtNew.Columns.Add("CompanyID", System.Type.GetType("System.String"));
                dtNew.Columns.Add("BillNo", System.Type.GetType("System.String"));
                dtNew.Columns.Add("StockID", System.Type.GetType("System.String"));

                #endregion 构造一个新的Datatable dtNew



                string companyId = string.Empty;
                string billNo = string.Empty;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    errorIndex = i + 7;
                    model.CompanyID = dt.Rows[i]["CompanyID"].ToString().Trim();
                    model.BillNo = dt.Rows[i]["BillNo"].ToString().Trim();
                    model.StockId = dt.Rows[i]["StockID"].ToString().Trim();

                    #region Delete

                    if (i > 0)
                    {
                        companyId = dt.Rows[i - 1]["CompanyID"].ToString().Trim();
                        billNo = dt.Rows[i - 1]["BillNo"].ToString().Trim();
                        if (companyId != model.CompanyID || billNo != model.BillNo)
                        {
                            string deleteSql = $@"
                                    Delete
                                    FROM goods.goods_DC_OrderForStock
                                    where CompanyId='{model.CompanyID}' and BillNo='{model.BillNo}' 
                                            ";
                            deleteHashSet.Add(deleteSql);
                        }

                    }
                    else
                    {
                        string deleteSql = $@"
                                    Delete
                                    FROM goods.goods_DC_OrderForStock
                                    where CompanyId='{model.CompanyID}' and BillNo='{model.BillNo}' 
                                            ";
                        deleteHashSet.Add(deleteSql);
                    }

                    #endregion Delete

                    DataRow dr = dtNew.NewRow();
                    dr["CompanyID"] = model.CompanyID;
                    dr["BillNo"] = model.BillNo;
                    dr["StockID"] = model.StockId;
                    dtNew.Rows.Add(dr);

                    index++;
                }
                //拼接删除的sql语句
                foreach (var deleteSql in deleteHashSet)
                {
                    cmdList.Add(new CommandInfo()
                    {
                        CommandText = deleteSql
                    });
                }
                //然后调用批量插入的方法
                Helper.ExecuteSqlTran(cmdList, dtNew, "goods.goods_DC_OrderForStock");
                if (dtError.Rows.Count > 0)
                {
                    var path = ExcelImporMapper.GetTemplatePath(Type);
                    result.IsSuccess = true;
                    result.ExtraInfo = "导入成功";
                    result.Message = $"成功导入{index}条数据,错误{dt.Rows.Count - index}条";
                    result.Url = ExcelUtil.ExportErrorExeclToDB(dtError, path, dictFields, "下载错误数据", num);
                    num++;
                }
                else
                {
                    result.IsSuccess = true;
                    result.ExtraInfo = "导入成功";
                    result.Message = $"成功导入{index}条数据,错误{dt.Rows.Count - index}条";
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                if (dtError.Rows.Count > 0)
                {
                    var path = ExcelImporMapper.GetTemplatePath(Type);
                    result.IsSuccess = false;
                    result.ExtraInfo = "导入失败";
                    result.Message = $"成功导入{index}条数据,错误{dt.Rows.Count - index}条";
                    result.Url = ExcelUtil.ExportErrorExeclToDB(dtError, path, dictFields, "下载错误数据", num);
                    num++;
                    return result;
                }
            }
            return result;
        }


        public override DataTable GetExportData(string Keys)
        {
            throw new NotImplementedException();
        }

        public void InsertToError(DataTable dtError, ProductionOrderWarehouseModel model)
        {
            DataRow dr = dtError.NewRow();
            dr["CompanyID"] = model.CompanyID;
            dr["BillNo"] = model.BillNo;
            dr["StockID"] = model.StockId;
            dtError.Rows.Add(dr);
        }

    }
}

